# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: env_util.py
# Time: 11:09

import os
import re

from common.util.file_util import get_sub_dir
from common.util.read_util import OperationIni


class EnvironmentConfiguration():
    def __init__(self):
        self.config = OperationIni("env.ini").get_ini_file_path_section_data("used_env")

    def get_apppackage_version(self):
        '''
        自动获取apk包名和版本信息
        :return: apppackage appversion
        '''
        apk_path = self.get_app_file_path()
        if os.path.exists(apk_path):
            cmd_str = r'aapt dump badging {}'.format(apk_path)
            try:
                with os.popen(cmd_str, "r") as f:
                    out_str = f.buffer.read().decode(encoding='utf8')

                    apkVersion = re.search(r"(\d\.){2,}\d", out_str).group()
                    appPackage = re.search("package: name='.+' versionCode", out_str).group().replace("package: name='",
                                                                                                      "").replace(
                        "' versionCode", "")
                    return apkVersion, appPackage
            except Exception as e:
                raise e
        else:
            return False

    def get_environment(self):
        '''
        获取环境信息，根据env.ini文件配置
        :return: 返回 TRUE FLASE
        '''
        env = self.config.get("environment_env")
        if env == "test":
            return "test"
        elif env == "pord":
            return "pord"
        else:
            return None

    def get_app_file_path(self):
        '''获取APP绝对路径'''
        file_path = None
        path = get_sub_dir("app")
        prod = OperationIni("env.ini").get_ini_option_data("used_env", "environment_env")
        try:
            for root, dirs, files in os.walk(path):
                for name in files:
                    if prod in name:
                        file_path = os.path.join(root, name)
            return file_path
        except Exception as e:
            raise e


if __name__ == '__main__':
    print(EnvironmentConfiguration().get_environment())
